package com.alibaba.algo.apiimpl.user;

import com.alibaba.algo.annotation.OperateLogAnnotation;
import com.alibaba.algo.constants.Constants;
import com.alibaba.algo.cooperation.common.BaseResult;
import com.alibaba.algo.cooperation.common.PagerEntity;
import com.alibaba.algo.cooperation.feign.vo.enums.OrgTypeEnum;
import com.alibaba.algo.cooperation.usercomponent.service.user.SysEmployeeService;
import com.alibaba.algo.cooperation.usercomponent.vo.req.user.*;
import com.alibaba.algo.cooperation.usercomponent.vo.res.user.EmployeeOrgAndPositionResponseVO;
import com.alibaba.algo.cooperation.usercomponent.vo.res.user.EmployeeOrgResVO;
import com.alibaba.algo.cooperation.usercomponent.vo.res.user.SelectEmployeeBaseAndOrgInfoResVO;
import com.alibaba.algo.core.base.CoreTools;
import com.alibaba.algo.core.base.Pager;
import com.alibaba.algo.core.base.YesOrNo;
import com.alibaba.algo.core.exception.BaseException;
import com.alibaba.algo.dao.user.SysEmployeeMapper;
import com.alibaba.algo.domain.user.*;
import com.alibaba.algo.dtos.user.SysPositionDTO;
import com.alibaba.algo.entity.user.*;
import com.alibaba.algo.enums.OperateTypeEnum;
import com.alibaba.algo.enums.ResourceTypeEnum;
import com.alibaba.algo.excellistener.SysEmployeeListener;
import com.alibaba.algo.exception.BaseErrorCode;
import com.alibaba.algo.exception.SysEmployeeErrorCode;
import com.alibaba.algo.util.StringUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 类SysEmployeeServiceImpl.java的实现描述：员工 serviceimpl
 *
 * @author nieganggang 2021-03-12 16:08:17
 */
@Slf4j
@RestController
public class SysEmployeeServiceImpl implements SysEmployeeService {

    @Autowired
    private SysEmployeeDomain sysEmployeeDomain;

    @Resource
    private SysEmployeeMapper sysEmployeeMapper;

    @Autowired
    private SysEmployeeOrgDomain sysEmployeeOrgDomain;

    @Autowired
    private SysEmployeePositionDomain sysEmployeePositionDomain;

    @Autowired
    private SysOrgDomain sysOrgDomain;

    @Autowired
    private SysPositionDomain sysPositionDomain;

    @Autowired
    private SysUserCacheServiceImpl sysUserCacheService;

    @Autowired
    private SysUserEmployeeDomain sysUserEmployeeDomain;

    @Autowired
    private SysEmployeeGroupDomain sysEmployeeGroupDomain;

    @Autowired
    private SysUserDomain sysUserDomain;

    private boolean hasMorePrimaryOrg(List<OrgAndPositionInfo> orgAndEmployeeInfoList) {
        Set<OrgAndPositionInfo> orgAndEmployeeInfoSet = new TreeSet<>(Comparator.comparing(OrgAndPositionInfo::getOrgId));
        orgAndEmployeeInfoSet.addAll(orgAndEmployeeInfoList);
        List<OrgAndPositionInfo> orgAndEmployeeInfoDistinctList = new ArrayList<>(orgAndEmployeeInfoSet);
        return orgAndEmployeeInfoDistinctList.stream()
                .filter(p -> YesOrNo.Y.name().equals(p.getIsPrimaryOrg()))
                .count() > 1;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public BaseResult insert(SaveEmployeeRequestVO vo) {
        // 校验工号唯一性
        this.checkEmployeeInfo(vo.getEmployeeCode(), vo.getMobilePhone(), vo.getEmail());
        this.checkEmployeeExpire(vo.getExpireStarttime(), vo.getExpireEndtime());
        // 前端校验相关参数
        if (CollectionUtils.isEmpty(vo.getOrgAndEmployeeInfoList())) {
            throw new BaseException(SysEmployeeErrorCode.EMPLOYEE_ORG_LIST_IS_EMPTY.getCode(), SysEmployeeErrorCode.EMPLOYEE_ORG_LIST_IS_EMPTY.getMessage());
        }
        if (hasMorePrimaryOrg(vo.getOrgAndEmployeeInfoList())) {
            throw new BaseException(SysEmployeeErrorCode.EMPLOYEE_PRIMARY_ORG_REPEAT.getCode(), SysEmployeeErrorCode.EMPLOYEE_PRIMARY_ORG_REPEAT.getMessage());
        }

        SysEmployee sysEmployee = new SysEmployee();
        BeanUtils.copyProperties(vo, sysEmployee);
        sysEmployeeDomain.insert(sysEmployee);
        Long employeeId = sysEmployee.getId();
        this.batchAddEmployeeOrgAndPositionInfo(employeeId, vo.getOrgAndEmployeeInfoList());
        return BaseResult.buildSuccess();
    }

    /**
     * 批量新增员工组织岗位信息
     *
     * @param employeeId             员工标识
     * @param orgAndEmployeeInfoList 组织岗位列表
     */
    private void batchAddEmployeeOrgAndPositionInfo(Long employeeId, List<OrgAndPositionInfo> orgAndEmployeeInfoList) {
        if (CollectionUtils.isEmpty(orgAndEmployeeInfoList)) {
            return;
        }
        List<Long> hasInsertOrg = new ArrayList<>();
        for (OrgAndPositionInfo orgAndPositionInfo : orgAndEmployeeInfoList) {
            Long orgId = orgAndPositionInfo.getOrgId();
            Long positionId = orgAndPositionInfo.getPositionId();
            //处理sys_employee_org重复记录的BUG
            if (!hasInsertOrg.contains(orgId)) {
                hasInsertOrg.add(orgId);
                SysEmployeeOrg sysEmployeeOrg = new SysEmployeeOrg();
                sysEmployeeOrg.setEmployeeId(employeeId);
                sysEmployeeOrg.setOrgId(orgId);
                sysEmployeeOrg.setIsPrimaryOrg(orgAndPositionInfo.getIsPrimaryOrg());
                sysEmployeeOrgDomain.insert(sysEmployeeOrg);
            }
            SysEmployeePosition sysEmployeePosition = new SysEmployeePosition();
            sysEmployeePosition.setEmployeeId(employeeId);
            sysEmployeePosition.setPositionId(positionId);
            sysEmployeePositionDomain.insert(sysEmployeePosition);
        }
    }

    /**
     * 校验用户信息
     *
     * @param employeeCode 用户工号
     */
    private void checkEmployeeInfo(String employeeCode, String phone, String email) {
        if (!StringUtils.isEmpty(employeeCode)) {
            // 校验用户工号全局唯一性
            SysEmployee userCode = new SysEmployee();
            userCode.setEmployeeCode(employeeCode.trim());
            List<SysEmployee> sysEmployeeList = sysEmployeeDomain.listByPara(userCode, null);
            if (!CollectionUtils.isEmpty(sysEmployeeList)) {
                throw new BaseException(SysEmployeeErrorCode.EMPLOYEE_CODE_REPEAT.getCode(), SysEmployeeErrorCode.EMPLOYEE_CODE_REPEAT.getMessage());
            }
        }
        // 校验手机号
//        if (!StringUtils.isEmpty(phone)) {
//            SysEmployee employeePhone = new SysEmployee();
//            employeePhone.setMobilePhone(phone.trim());
//            List<SysEmployee> sysEmployeeList = sysEmployeeDomain.listByPara(employeePhone, null);
//            if (!CollectionUtils.isEmpty(sysEmployeeList)) {
//                throw new BaseException(SysEmployeeErrorCode.EMPLOYEE_PHONE_REPEAT.getCode(), SysEmployeeErrorCode.EMPLOYEE_PHONE_REPEAT.getMessage());
//            }
//        }
        // 校验邮箱
//        if (!StringUtils.isEmpty(email)) {
//            SysEmployee employeeEmail = new SysEmployee();
//            employeeEmail.setEmail(email.trim());
//            List<SysEmployee> sysEmployeeList = sysEmployeeDomain.listByPara(employeeEmail, null);
//            if (!CollectionUtils.isEmpty(sysEmployeeList)) {
//                throw new BaseException(SysEmployeeErrorCode.EMPLOYEE_EMAIL_REPEAT.getCode(), SysEmployeeErrorCode.EMPLOYEE_EMAIL_REPEAT.getMessage());
//            }
//        }
    }

    /**
     * 校验员工有效期时间
     *
     * @param startDate 起止时间
     * @param endDate   截止时间
     */
    private void checkEmployeeExpire(Date startDate, Date endDate) {
        if (!ObjectUtils.isEmpty(startDate) && (!ObjectUtils.isEmpty(endDate))) {
            if (endDate.before(startDate)) {
                throw new BaseException(SysEmployeeErrorCode.END_DATE_IS_BEFORE_START.getCode(), SysEmployeeErrorCode.END_DATE_IS_BEFORE_START.getMessage());
            }
        }
    }

    /**
     * 员工信息更新
     *
     * @param vo 更新参数
     * @return 更新结果
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public BaseResult update(UpdateEmployeeRequestVO vo) {
        if (null == vo || ObjectUtils.isEmpty(vo.getId())) {
            throw new BaseException(BaseErrorCode.EMPLOYEE_ID_IS_NULL.getCode(), BaseErrorCode.EMPLOYEE_ID_IS_NULL.getMessage());
        }
        // 组织、岗位信息为空的话后续不会更新
        /*if (CollectionUtils.isEmpty(vo.getOrgAndEmployeeInfoList())) {
            throw new BaseException(SysEmployeeErrorCode.EMPLOYEE_ORG_LIST_IS_EMPTY.getCode(), SysEmployeeErrorCode.EMPLOYEE_ORG_LIST_IS_EMPTY.getMessage());
        }*/
        SysEmployee oldEmployee = sysEmployeeDomain.getById(vo.getId());
        if (null == oldEmployee) {
            throw new BaseException(BaseErrorCode.EMPLOYEE_NOT_EXISTS.getCode(), BaseErrorCode.EMPLOYEE_NOT_EXISTS.getMessage());
        }
        if (ObjectUtils.isEmpty(vo.getEmployeeCode()) || vo.getEmployeeCode().equals(oldEmployee.getEmployeeCode())) {
            vo.setEmployeeCode(null);
        }
        this.checkEmployeeInfo(vo.getEmployeeCode(), vo.getMobilePhone(), vo.getEmail());
        this.checkEmployeeExpire(vo.getExpireStarttime(), vo.getExpireEndtime());
        List<OrgAndPositionInfo> orgAndPositionInfos = null;
        // 如果组织列表非空,需要先更新为删除状态
        if (!CollectionUtils.isEmpty(vo.getOrgAndEmployeeInfoList())) {
            orgAndPositionInfos = vo.getOrgAndEmployeeInfoList().stream().distinct().collect(Collectors.toList());
            this.deleteEmployeeRelatedOrgAndPosition(vo.getId());
            if (hasMorePrimaryOrg(vo.getOrgAndEmployeeInfoList())) {
                throw new BaseException(SysEmployeeErrorCode.EMPLOYEE_PRIMARY_ORG_REPEAT.getCode(), SysEmployeeErrorCode.EMPLOYEE_PRIMARY_ORG_REPEAT.getMessage());
            }
        }
        SysEmployee sysEmployee = new SysEmployee();
        BeanUtils.copyProperties(vo, sysEmployee);
        int iRtn = sysEmployeeDomain.updateById(sysEmployee);
        // 批量新增岗位信息
        this.batchAddEmployeeOrgAndPositionInfo(vo.getId(), orgAndPositionInfos);
        if (iRtn > 0) {
            // 删除缓存
            sysUserCacheService.deleteUserFromCacheByEmployeeUpdate(Arrays.asList(vo.getId()));
        }
        return BaseResult.buildSuccess();
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true, rollbackFor = Exception.class)
    public PagerEntity selectPage(SelectEmployeeListRequestVO vo) {
        long total = sysEmployeeMapper.countByCustomPara(vo);
        Integer pageIndex = vo.getPageIndex();
        Integer pageSize = vo.getPageSize();
        Pager pager = Pager.newInstance(total, pageIndex, pageSize);
        LinkedHashMap<String, Object> sortMap = new LinkedHashMap<>();
        sortMap.put("gmtCreated", "DESC");
        sortMap.put("id", "DESC");
        List<SelectEmployeeBaseAndOrgInfoResVO> result = sysEmployeeMapper.pageByCustomPara(vo, pager.getStart(), pager.getEnd(), CoreTools.getSortStr(sortMap));
        for (SelectEmployeeBaseAndOrgInfoResVO selectEmployeeBaseAndOrgInfoResVO : result) {
            // 查询组织岗位信息
            List<EmployeeOrgResVO> employeeOrgList = sysEmployeeOrgDomain.selectEmployeeOrgListByEmployeeId(selectEmployeeBaseAndOrgInfoResVO.getId());
            selectEmployeeBaseAndOrgInfoResVO.setOrgList(employeeOrgList);
            selectEmployeeBaseAndOrgInfoResVO.setPositionList(sysEmployeePositionDomain.selectEmployeePositionListByEmployeeId(selectEmployeeBaseAndOrgInfoResVO.getId()));

            Set<Long> orgSet = new HashSet<>();
            Long primaryOrgId = null;
            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(employeeOrgList)) {
                for (EmployeeOrgResVO employeeOrgResVO : employeeOrgList) {
                    if ("Y".equals(employeeOrgResVO.getIsPrimaryOrg())) {
                        orgSet.add(employeeOrgResVO.getEmployeeOrgId());
                        if (null == primaryOrgId) {
                            primaryOrgId = employeeOrgResVO.getEmployeeOrgId();
                        }
                    }
                }
            }

            // 查询员工所归属的公司
            String companyName = Constants.COMAC_COMPANY_NAME;
            if (null != primaryOrgId) {
                List<SysOrg> sysOrgList = sysOrgDomain.selectOrgIdListRecursiveToRoot(primaryOrgId);
                if (!CollectionUtils.isEmpty(sysOrgList)) {
                    for (SysOrg sysOrg : sysOrgList) {
                        //是公司，其不是中国商飞
                        if (OrgTypeEnum.COMPANY.getCode().equals(sysOrg.getOrgType())
                                && sysOrg.getId() != 0) {
                            companyName = sysOrg.getOrgName();
                            break;
                        }
                    }
                }
            }
            selectEmployeeBaseAndOrgInfoResVO.setCompanyName(companyName);

            List<EmployeeOrgAndPositionResponseVO> employeeOrgAndPosList = sysEmployeeDomain.selectOrgAndPositionList(selectEmployeeBaseAndOrgInfoResVO.getId());
            if (!ObjectUtils.isEmpty(employeeOrgAndPosList)) {
                selectEmployeeBaseAndOrgInfoResVO.setOrgAndPositionList(employeeOrgAndPosList);
            } else {
                if (!ObjectUtils.isEmpty(employeeOrgList)) {
                    employeeOrgAndPosList = new ArrayList<>();
                    for (EmployeeOrgResVO employeeOrgResVO : employeeOrgList) {
                        EmployeeOrgAndPositionResponseVO employeeOrgAndPositionResponseVO = new EmployeeOrgAndPositionResponseVO();
                        BeanUtils.copyProperties(employeeOrgResVO, employeeOrgAndPositionResponseVO);
                        employeeOrgAndPosList.add(employeeOrgAndPositionResponseVO);
                    }
                    selectEmployeeBaseAndOrgInfoResVO.setOrgAndPositionList(employeeOrgAndPosList);
                }
            }

            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(selectEmployeeBaseAndOrgInfoResVO.getOrgAndPositionList())) {
                for (EmployeeOrgAndPositionResponseVO item : selectEmployeeBaseAndOrgInfoResVO.getOrgAndPositionList()) {
                    if (orgSet.contains(item.getEmployeeOrgId())) {
                        item.setIsPrimaryOrg("Y");
                    } else {
                        item.setIsPrimaryOrg("N");
                    }
                }
            }
        }
        return new PagerEntity(total, pager.getTotalPages(), pageSize, pageIndex, result);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true, rollbackFor = Exception.class)
    public PagerEntity selectPageByIds(SelectEmployeeListRequestVO vo) {
        long total = sysEmployeeMapper.countBySelect(vo);
        Integer pageIndex = vo.getPageIndex();
        Integer pageSize = vo.getPageSize();
        Pager pager = Pager.newInstance(total, pageIndex, pageSize);
        LinkedHashMap<String, Object> sortMap = new LinkedHashMap<String, Object>();
        sortMap.put("gmtCreated", "DESC");
        sortMap.put("id", "DESC");
        List<SelectEmployeeBaseAndOrgInfoResVO> result = sysEmployeeMapper.pageByIds(vo, pager.getStart(), pager.getEnd(), CoreTools.getSortStr(sortMap));
        for (SelectEmployeeBaseAndOrgInfoResVO selectEmployeeBaseAndOrgInfoResVO : result) {
            // 查询组织岗位信息
            List<EmployeeOrgResVO> employeeOrgList = sysEmployeeOrgDomain.selectEmployeeOrgListByEmployeeId(selectEmployeeBaseAndOrgInfoResVO.getId());
            selectEmployeeBaseAndOrgInfoResVO.setOrgList(employeeOrgList);
            selectEmployeeBaseAndOrgInfoResVO.setPositionList(sysEmployeePositionDomain.selectEmployeePositionListByEmployeeId(selectEmployeeBaseAndOrgInfoResVO.getId()));
            List<EmployeeOrgAndPositionResponseVO> employeeOrgAndPosList = sysEmployeeDomain.selectOrgAndPositionList(selectEmployeeBaseAndOrgInfoResVO.getId());
            if (!ObjectUtils.isEmpty(employeeOrgAndPosList)) {
                selectEmployeeBaseAndOrgInfoResVO.setOrgAndPositionList(employeeOrgAndPosList);
            } else {
                if (!ObjectUtils.isEmpty(employeeOrgList)) {
                    employeeOrgAndPosList = new ArrayList<>();
                    for (EmployeeOrgResVO employeeOrgResVO : employeeOrgList) {
                        EmployeeOrgAndPositionResponseVO employeeOrgAndPositionResponseVO = new EmployeeOrgAndPositionResponseVO();
                        BeanUtils.copyProperties(employeeOrgResVO, employeeOrgAndPositionResponseVO);
                        employeeOrgAndPosList.add(employeeOrgAndPositionResponseVO);
                    }
                    selectEmployeeBaseAndOrgInfoResVO.setOrgAndPositionList(employeeOrgAndPosList);
                }
            }

        }
        return new PagerEntity(total, pager.getTotalPages(), pageSize, pageIndex, result);
    }

    /**
     * 删除员工关联的组织和岗位信息
     *
     * @param employeeId 员工标识
     */
    private void deleteEmployeeRelatedOrgAndPosition(Long employeeId) {
        if (ObjectUtils.isEmpty(employeeId)) {
            throw new BaseException(BaseErrorCode.EMPLOYEE_ID_IS_NULL.getCode(), BaseErrorCode.EMPLOYEE_ID_IS_NULL.getMessage());
        }
        // 更新组织员工表sys_employee_org
        SysEmployeeOrg sysEmployeeOrg = new SysEmployeeOrg();
        sysEmployeeOrg.setEmployeeId(employeeId);
        sysEmployeeOrg.setIsDeleted(YesOrNo.Y.name());
        sysEmployeeOrg.setGmtModified(LocalDateTime.now());
        int iCnt = sysEmployeeOrgDomain.updateById(sysEmployeeOrg);
        log.info("sysEmployeeOrgDomain.updateById employeeId={}, result={}", employeeId, iCnt);
        // 更新员工岗位表sys_employee_position
        SysEmployeePosition sysEmployeePosition = new SysEmployeePosition();
        sysEmployeePosition.setEmployeeId(employeeId);
        sysEmployeePosition.setIsDeleted(YesOrNo.Y.name());
        sysEmployeePosition.setGmtModified(LocalDateTime.now());
        iCnt = sysEmployeePositionDomain.updateById(sysEmployeePosition);
        log.info("sysEmployeePositionDomain.updateById employeeId={}, result={}", employeeId, iCnt);
    }

    private void updateEmployeeRelatedOrgAndPositionLastModified(Long employeeId, LocalDateTime lastModifyTime) {
        if (ObjectUtils.isEmpty(employeeId)) {
            throw new BaseException(BaseErrorCode.EMPLOYEE_ID_IS_NULL.getCode(), BaseErrorCode.EMPLOYEE_ID_IS_NULL.getMessage());
        }
        // 更新组织员工表sys_employee_org
        SysEmployeeOrg sysEmployeeOrg = new SysEmployeeOrg();
        sysEmployeeOrg.setEmployeeId(employeeId);
        sysEmployeeOrg.setIsDeleted(YesOrNo.N.name());
        sysEmployeeOrg.setGmtModified(LocalDateTime.now());
        int iCnt = sysEmployeeOrgDomain.updateByEmployeeIdLastModified(sysEmployeeOrg, lastModifyTime);
        log.info("sysEmployeeOrgDomain.updateByEmployeeIdLastModified employeeId={}, lastModifyTime={}, result={}", employeeId, lastModifyTime, iCnt);
        // 更新员工岗位表sys_employee_position
        SysEmployeePosition sysEmployeePosition = new SysEmployeePosition();
        sysEmployeePosition.setEmployeeId(employeeId);
        sysEmployeePosition.setIsDeleted(YesOrNo.N.name());
        sysEmployeePosition.setGmtModified(LocalDateTime.now());
        iCnt = sysEmployeePositionDomain.updateByEmployeeIdLastModified(sysEmployeePosition, lastModifyTime);
        log.info("sysEmployeePositionDomain.updateByEmployeeIdLastModified employeeId={}, lastModifyTime={}, result={}", employeeId, lastModifyTime, iCnt);
    }

    private void deleteEmployeeRelatedUser(Long employeeId) {
        if (ObjectUtils.isEmpty(employeeId)) {
            throw new BaseException(BaseErrorCode.EMPLOYEE_ID_IS_NULL.getCode(), BaseErrorCode.EMPLOYEE_ID_IS_NULL.getMessage());
        }
        SysUserEmployee sysUserEmployeeCon = new SysUserEmployee();
        sysUserEmployeeCon.setEmployeeId(employeeId);
        List<SysUserEmployee> sysUserEmployeeList = sysUserEmployeeDomain.listByEmployeeId(sysUserEmployeeCon);
        if (CollectionUtils.isEmpty(sysUserEmployeeList)) {
            log.info("没有找到有效的用户员工关联关系,employeeId={}", employeeId);
            return;
        }
        for (SysUserEmployee sysUserEmployee : sysUserEmployeeList) {
            sysUserEmployee.setIsDeleted(YesOrNo.Y.name());
            sysUserEmployee.setGmtModified(LocalDateTime.now());
            if (null != sysUserEmployee.getId() && sysUserEmployee.getId() > 0) {
                int iCnt = sysUserEmployeeDomain.updateById(sysUserEmployee);
                log.info("sysUserEmployeeDomain.updateById employeeId={}, result={}", employeeId, iCnt);

                //清除掉用户表的工号
                if (iCnt > 0) {
                    SysUser sysUser = new SysUser();
                    sysUser.setId(sysUserEmployee.getUserId());
                    sysUser.setEmployeeCode("");
                    sysUser.setGmtModified(LocalDateTime.now());
                    iCnt = sysUserDomain.updateEmployeeCodeByUserId(sysUser);
                    log.info("sysUserDomain.updateById userId={}, result={}", employeeId, iCnt);
                }
            }
        }
    }

    private void updateEmployeeRelatedUserLastModified(Long employeeId, LocalDateTime lastModifyTime) {
        if (ObjectUtils.isEmpty(employeeId)) {
            throw new BaseException(BaseErrorCode.EMPLOYEE_ID_IS_NULL.getCode(), BaseErrorCode.EMPLOYEE_ID_IS_NULL.getMessage());
        }
        SysUserEmployee sysUserEmployeeCon = new SysUserEmployee();
        sysUserEmployeeCon.setEmployeeId(employeeId);
        List<SysUserEmployee> sysUserEmployeeList = sysUserEmployeeDomain.listByEmployeeIdLastModified(sysUserEmployeeCon, lastModifyTime);
        if (CollectionUtils.isEmpty(sysUserEmployeeList)) {
            log.info("没有找到有效的用户员工关联关系,employeeId={}", employeeId);
            return;
        }
        for (SysUserEmployee sysUserEmployee : sysUserEmployeeList) {
            sysUserEmployee.setIsDeleted(YesOrNo.N.name());
            sysUserEmployee.setGmtModified(LocalDateTime.now());
            if (null != sysUserEmployee.getId() && sysUserEmployee.getId() > 0) {
                int iCnt = sysUserEmployeeDomain.updateByIdWithIsDeleted(sysUserEmployee);
                log.info("sysUserEmployeeDomain.updateByIdWithIsDeleted id={}, result={}", sysUserEmployee.getId(), iCnt);
                //恢复用户表的工号
                if (iCnt > 0) {
                    SysUser sysUser = new SysUser();
                    sysUser.setId(sysUserEmployee.getUserId());
                    SysEmployee sysEmployeeFromDB = sysEmployeeDomain.getById(sysUserEmployee.getEmployeeId());
                    if (!ObjectUtils.isEmpty(sysEmployeeFromDB) && org.apache.commons.lang3.StringUtils.isNotEmpty(sysEmployeeFromDB.getEmployeeCode())) {
                        sysUser.setEmployeeCode(sysEmployeeFromDB.getEmployeeCode());
                        sysUser.setGmtModified(LocalDateTime.now());
                        iCnt = sysUserDomain.updateEmployeeCodeByUserId(sysUser);
                        log.info("sysUserDomain.updateEmployeeCodeByUserId userId={}, result={}", sysUserEmployee.getUserId(), iCnt);
                    }
                }
            }
        }
    }

    private void deleteEmployeeRelatedGroup(Long employeeId) {
        if (ObjectUtils.isEmpty(employeeId)) {
            throw new BaseException(BaseErrorCode.EMPLOYEE_ID_IS_NULL.getCode(), BaseErrorCode.EMPLOYEE_ID_IS_NULL.getMessage());
        }
        SysEmployeeGroup sysEmployeeGroup = SysEmployeeGroup.builder().build();
        sysEmployeeGroup.setEmployeeId(employeeId);
        sysEmployeeGroup.setIsDeleted(YesOrNo.Y.name());
        sysEmployeeGroup.setGmtModified(LocalDateTime.now());
        sysEmployeeGroupDomain.updateByEmployeeId(sysEmployeeGroup);
    }

    private void updateEmployeeRelatedGroupLastModified(Long employeeId, LocalDateTime lastModifyTime) {
        if (ObjectUtils.isEmpty(employeeId)) {
            throw new BaseException(BaseErrorCode.EMPLOYEE_ID_IS_NULL.getCode(), BaseErrorCode.EMPLOYEE_ID_IS_NULL.getMessage());
        }
        SysEmployeeGroup sysEmployeeGroup = SysEmployeeGroup.builder().build();
        sysEmployeeGroup.setEmployeeId(employeeId);
        sysEmployeeGroup.setIsDeleted(YesOrNo.N.name());
        sysEmployeeGroup.setGmtModified(LocalDateTime.now());
        int iCnt = sysEmployeeGroupDomain.updateByEmployeeIdLastModified(sysEmployeeGroup, lastModifyTime);
        log.info("sysUserEmployeeDomain.updateByEmployeeIdLastModified employeeId={}, result={}", employeeId, iCnt);
    }

    /**
     * 删除员工
     *
     * @param employeeIdList 员工列表
     * @return 删除结果
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public BaseResult delete(List<Long> employeeIdList) {
        if (CollectionUtils.isEmpty(employeeIdList)) {
            log.info("SysEmployeeServiceImpl delete employeeIdList is null");
            return BaseResult.buildError("参数不能为空");
        }
        for (Long employeeId : employeeIdList) {
            // 删除员工
            SysEmployee sysEmployee = new SysEmployee();
            sysEmployee.setId(employeeId);
            sysEmployee.setIsDeleted(YesOrNo.Y.name());
            sysEmployee.setGmtModified(LocalDateTime.now());
            int iCnt = sysEmployeeDomain.updateById(sysEmployee);
            log.info("sysEmployeeDomain.updateById result={}", iCnt);
            // 删除此员工与之关联的岗位和组织信息
            deleteEmployeeRelatedOrgAndPosition(employeeId);
            // 解除员工和用户的关系
            deleteEmployeeRelatedUser(employeeId);
            // 解除员工和人员组的关系
            deleteEmployeeRelatedGroup(employeeId);
        }
        // 批量删除缓存
        sysUserCacheService.deleteUserFromCacheByEmployeeUpdate(employeeIdList);
        return BaseResult.buildSuccess();
    }

    /**
     * 删除当前员工的组织和岗位关联关系
     *
     * @param deleteOrgAndPositionReqVOList 组织岗位信息
     * @return 组织和岗位关联列表
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public BaseResult deleteOrgAndPosition(List<DeleteOrgAndPositionReqVO> deleteOrgAndPositionReqVOList) {
        if (CollectionUtils.isEmpty(deleteOrgAndPositionReqVOList)) {
            return BaseResult.buildSuccess();
        }
        for (DeleteOrgAndPositionReqVO deleteOrgAndPositionReqVO : deleteOrgAndPositionReqVOList) {
            SysEmployeePosition sysEmployeePosition = new SysEmployeePosition();
            sysEmployeePosition.setId(deleteOrgAndPositionReqVO.getEmployeePositionId());
            sysEmployeePosition.setIsDeleted(YesOrNo.Y.name());
            sysEmployeePosition.setGmtModified(LocalDateTime.now());
            if (null != sysEmployeePosition && null != sysEmployeePosition.getId() && sysEmployeePosition.getId() > 0) {
                sysEmployeePositionDomain.updateById(sysEmployeePosition);
            }
            SysEmployeeOrg sysEmployeeOrg = new SysEmployeeOrg();
            sysEmployeeOrg.setId(deleteOrgAndPositionReqVO.getEmployeeOrgId());
            sysEmployeeOrg.setIsDeleted(YesOrNo.Y.name());
            sysEmployeeOrg.setGmtModified(LocalDateTime.now());
            if (null != sysEmployeeOrg && null != sysEmployeeOrg.getId() && sysEmployeeOrg.getId() > 0) {
                sysEmployeeOrgDomain.updateById(sysEmployeeOrg);
            }
        }
        return BaseResult.buildSuccess();
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public BaseResult revalidate(List<Long> employeeIdList) {
        if (CollectionUtils.isEmpty(employeeIdList)) {
            log.info("SysEmployeeServiceImpl revalidate employeeIdList is null");
            return BaseResult.buildError("参数不能为空");
        }
        for (Long employeeId : employeeIdList) {
            //根据userId查询最后修改时间
            SysEmployee sysEmployeeFromDB = sysEmployeeMapper.getByIdWithIsDeleted(employeeId);
            LocalDateTime lastModifyTime = null;
            if (!ObjectUtils.isEmpty(sysEmployeeFromDB)) {
                lastModifyTime = sysEmployeeFromDB.getGmtModified();
            }
            // 恢复员工
            SysEmployee sysEmployee = new SysEmployee();
            sysEmployee.setId(employeeId);
            sysEmployee.setIsDeleted(YesOrNo.N.name());
            sysEmployee.setGmtModified(LocalDateTime.now());
            int iCnt = sysEmployeeDomain.updateByIdWithIsDeleted(sysEmployee);
            log.info("SysEmployeeServiceImpl revalidate: sysEmployeeDomain.updateByIdWithIsDeleted result={}", iCnt);
            // 恢复此员工与之关联的岗位和组织信息
            updateEmployeeRelatedOrgAndPositionLastModified(employeeId, lastModifyTime);
            // 恢复员工和用户的关系
            updateEmployeeRelatedUserLastModified(employeeId, lastModifyTime);
            // 恢复员工和人员组的关系
            updateEmployeeRelatedGroupLastModified(employeeId, lastModifyTime);
        }
        // 批量删除缓存
        sysUserCacheService.deleteUserFromCacheByEmployeeUpdate(employeeIdList);
        return BaseResult.buildSuccess();
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true, rollbackFor = Exception.class)
    public BaseResult qryOrgAndPosition(SelectEmployeeDetailRequestVO vo) {
        List<EmployeeOrgAndPositionResponseVO> result = sysEmployeeDomain.selectOrgAndPositionList(vo.getEmployeeId());
        return BaseResult.buildSuccess(result);
    }

    /**
     * 批量导入员工
     *
     * @param file
     * @return
     */
    @Override
    public BaseResult importBatch(MultipartFile file) {
        InputStream inputStream;
        String[] strings = Objects.requireNonNull(file.getOriginalFilename()).split("\\.");
        String fileType = strings[strings.length - 1];
        if (StringUtil.isEmpty(fileType)) {
            return BaseResult.buildError(-1, "请上传xls或者xlsx类型文档。");
        }
        fileType = fileType.toLowerCase();
        if (!(fileType.equals(StringUtil.XLSX)
                || fileType.equals(StringUtil.XLS))) {
            return BaseResult.buildError(-1, "请上传xls或者xlsx类型文档。");
        }
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            log.error("import employee io error=={}", e);
            return BaseResult.buildError(-1, e);
        }
        SysEmployeeListener listener = new SysEmployeeListener(sysEmployeeDomain);
        try {
            EasyExcel.read(inputStream, SysEmployee.class, listener).sheet().doRead();
        } catch (Exception e) {
            log.error("read error={}", e);
            return BaseResult.buildError(-1, e.getMessage());
        }
        String s = listener.makeMsg();
        return BaseResult.buildSuccess(s);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @OperateLogAnnotation(resouceType = ResourceTypeEnum.SYNC_EMPLOYEE_ORG_POS_REL, operateType = OperateTypeEnum.DELETE)
    public BaseResult deleteEmployeePosOrgRelByMid(String mid) {
        if (StringUtils.isEmpty(mid)) {
            throw new BaseException(BaseErrorCode.MID_ID_IS_NULL.getCode(), BaseErrorCode.MID_ID_IS_NULL.getMessage());
        }
        log.info("SysEmployeeServiceImpl deleteEmployeePosOrgRelByMid mid:{}", mid);
        //根据mid查询
        SysEmployeePosition param = new SysEmployeePosition();
        param.setMid(mid);
        Long employeeId = null;
        Long positionId = null;
        Long orgId = null;
        List<SysEmployeePosition> employeePositionList = sysEmployeePositionDomain.listByPara(param, null);
        if (!ObjectUtils.isEmpty(employeePositionList)) {
            SysEmployeePosition sysEmployeePosition = employeePositionList.get(0);
            employeeId = sysEmployeePosition.getEmployeeId();
            positionId = sysEmployeePosition.getPositionId();
            //根据岗位id查询组织
            SysPosition positionParam = new SysPosition();
            positionParam.setId(positionId);
            SysPosition sysPosition = sysPositionDomain.getPositionDetail(positionParam);
            log.info("SysEmployeeServiceImpl deleteEmployeePosOrgRelByMid sysPosition:{}", JSON.toJSONString(sysPosition));
            Set<Long> positionIdSet = new HashSet<>();
            if (!ObjectUtils.isEmpty(sysPosition) && null != sysPosition.getOrgId()) {
                orgId = sysPosition.getOrgId();
                //根据组织id查询组织下岗位
                List<SysPositionDTO> sysPositionList = sysPositionDomain.selectListByOrgIdAndEmployeeId(sysPosition.getOrgId(), employeeId);
                //人员所在组织下所有岗位id集合
                if (!ObjectUtils.isEmpty(sysPositionList)) {
                    sysPositionList.stream().forEach(item -> {
                        positionIdSet.add(item.getId());
                    });
                }
            }
            if (ObjectUtils.isEmpty(positionIdSet) || positionIdSet.size() <= 1) {//组织下无其他的岗位
                //删除人员和组织关联关系
                if (null != employeeId && null != orgId) {
                    //log.info("SysEmployeeServiceImpl deleteEmployeePosOrgRelByMid deleteEmployeeOrg,employeeId:{},orgId:{}",employeeId,orgId);
                    //sysEmployeeOrgDomain.deleteByEmployeeIdAndOrgId(employeeId,orgId);
                    SysEmployeeOrg sysEmployeeOrg = new SysEmployeeOrg();
                    sysEmployeeOrg.setOrgId(orgId);
                    sysEmployeeOrg.setEmployeeId(employeeId);
                    sysEmployeeOrg.setIsDeleted(YesOrNo.Y.name());
                    sysEmployeeOrg.setModifier(Constants.ORIGIN_SAP);
                    sysEmployeeOrg.setGmtModified(LocalDateTime.now());
                    int iUpEmpOrgRtn = sysEmployeeOrgDomain.updateByEmployeeIdAndOrgId(sysEmployeeOrg);
                    log.info("SysEmployeeServiceImpl.deleteEmployeePosOrgRelByMid iUpEmpOrgRtn:{},orgId:{},employeeId:{}", iUpEmpOrgRtn, orgId, employeeId);
                }
            }
            //删除人员和岗位关联关系
            //log.info("SysEmployeeServiceImpl deleteEmployeePosOrgRelByMid deleteEmployeePosition,mid:{}",mid);
            //sysEmployeePositionDomain.deleteByMid(mid);
            SysEmployeePosition sysEmployeePositionParam = new SysEmployeePosition();
            sysEmployeePositionParam.setMid(mid);
            sysEmployeePositionParam.setIsDeleted(YesOrNo.Y.name());
            sysEmployeePositionParam.setModifier(Constants.ORIGIN_SAP);
            sysEmployeePositionParam.setGmtModified(LocalDateTime.now());
            int iUpEmpPosRtn = sysEmployeePositionDomain.logicDeleteByMid(sysEmployeePositionParam);
            log.info("SysEmployeeServiceImpl.deleteEmployeePosOrgRelByMid iUpEmpOrgRtn:{},mid:{}", iUpEmpPosRtn, mid);

            // 删除缓存
            if (null != employeeId && employeeId > 0) {
                sysUserCacheService.deleteUserFromCacheByEmployeeUpdate(Arrays.asList(employeeId));
            }
        }
        return BaseResult.buildSuccess();
    }
}
